<?php

namespace App\Repositories\Eloquent\Biz;

use Illuminate\Container\Container as App;
use App\Repositories\Eloquent\Repository;
use App\Repositories\Eloquent\Mgt\BookRepository as Book;

class BorrowRepository extends Repository
{
    protected $book;
    /**
     * @param App
     */
    public function __construct(App $app, Book $book)
    {
        parent::__construct($app);
        
        $this->book = $book;
    }

    /**
     * 指定模型名称
     *
     * @return mixed
     */
    function model()
    {
        return 'App\Models\Biz\Borrow';
    }
    
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($query = '')
    {
        // 获取分页数据
        if (!$query) {

            $result = $this->model->with('user','book')->orderBy('date', 'desc');
            
        } else {
            
            $map = $this->book->index($query)->pluck('id');
            
            $result = $this->wheres($map);
        }

        return $result;
    }


    public function show($id)
    {
        $borrow = $this->find($id);

        if (!$borrow) 
            return $this->responseFail(404, '借阅记录不正确');

        return $borrow;
    }

    //借阅
    public function set($user, $activity, $book)
    {
        $result = $this->create([
            'aid'           => $activity->id,
            'uid'           => $user->id,
            'account'       => $user->account,
            'bookid'        => $book->id,
            'date'          => time(),
            'date_begin'    => strtotime(date('Y-m-d')),
            'date_end'      => strtotime(date("Y-m-d", strtotime("+1 week")) ),
            'status'        => \App\Models\Biz\Borrow::BORROW_STATUS_UNRETURN,
        ]);

        return $result;
    }

    //还书
    public function rset($borrow, $activity)
    {
        $this->update([
            'rid'         => $activity->id,
            'status'      => \App\Models\Biz\Borrow::BORROW_STATUS_RETURNED,
            'date_return' => time(),            
        ], $borrow->id);
    }

    /**
     * 因ISBN会对应多本书籍
     * 所以根据ISBN获取的ID过滤掉没在借阅记录里的书籍
     * @param  [type] $lists [description]
     * @return [type]        [description]
     */
    public function wheres($lists)
    {
        return $this->model
                ->unreturn()
                ->whereIn('bookid', $lists)                
                ->orderBy('id','desc');
    }

    //是否重复的借阅
    public function occupied($request)
    {
        return $this->model
            ->where('aid', $request->aid)
            ->where('uid', $request->uid)
            ->where('bookid', $request->bid)
            ->unreturn()
            ->first();
    }
}